/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.posplus.losspreventiondataimporter.importer;

import com.posplus.lossprevention.APDAOFactory;
import com.posplus.lossprevention.mapping.Registers;
import com.posplus.lossprevention.mapping.Stores;
import com.posplus.strack.mapping.LaneInfo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.posplus.losspreventiondataimporter.service.LaneInfoService;
import com.posplus.losspreventiondataimporter.service.RegistersService;
import com.posplus.losspreventiondataimporter.service.StoresService;
import com.posplus.losspreventiondataimporter.util.ListToMap;
import org.apache.log4j.Logger;

/**
 *
 * @author scottw
 */
public class LaneInfoImporter {

    private APDAOFactory lpFactory;
    private LaneInfoService laneInfoService;
    private String storeCode;
    
    public LaneInfoImporter(LaneInfoService laneInfoService, APDAOFactory lpFactory) {
        this.lpFactory = lpFactory;
        this.laneInfoService = laneInfoService;
    }

    public void dataImport() {
        List<LaneInfo> laneInfos = laneInfoService.getAll();
        mapAndPersist(laneInfos, lpFactory);
    }
    
    private void mapAndPersist(List<LaneInfo> laneInfo, APDAOFactory lpFactory){
        List<Registers> mappedRegisters = new ArrayList<Registers>();
        StoresService storeService = new StoresService(lpFactory);
        Map<String, Stores> stores = ListToMap.storesToMap(storeService.getAll());
        
        Iterator<LaneInfo> iter = laneInfo.iterator();
        while (iter.hasNext()) {
            LaneInfo next = iter.next();
            
            try{
                Stores store = stores.get(storeCode);
                if(store == null)
                    throw new RuntimeException("Store " + storeCode + " not found");
                
                Registers register = new Registers(store, next.getRetailRegisterNo());
                mappedRegisters.add(register);
            }catch(RuntimeException ex){
                Logger.getLogger(LaneInfoImporter.class).debug(ex);
            }
        }
        
        if(mappedRegisters.size() > 0){
            RegistersService registersService = new RegistersService(lpFactory);
            //registersService.bulkInsert(mappedRegisters);
	    registersService.saveAll(mappedRegisters);
        }
    }

    public String getStoreCode() {
        return storeCode;
    }

    public void setStoreCode(String storeCode) {
        this.storeCode = storeCode;
    }
    
}
